package com.schooleducation.controller.teacher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.schooleducation.entity.Lesson;
import com.schooleducation.entity.LessonOneType;
import com.schooleducation.entity.User;
import com.schooleducation.service.ServiceFactory;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.JsonConfig;

@Controller
@RequestMapping("/teacher/publishLesson")
public class PublicLessonController {

	@Resource(name = "serviceFac")
	private ServiceFactory serviceFac;
	
	private List<LessonOneType> lessonOneTypes;
	
	/**
	 * 获取发布课程页面
	 * @param session
	 * @param model
	 * @return
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String getPage(HttpSession session, Model model) {
		User teacher = (User) session.getAttribute("teacher");
		if (teacher != null) {
			model.addAttribute("teacher", teacher);
			lessonOneTypes = serviceFac.getLessonService().getLessonTypeAll();
			model.addAttribute("lessonOneType", lessonOneTypes);
			
			return "teacher/publishLesson";
		} else {
			return "redirect:../login";
		}		
	}
	
	/**
	 * 动态获取获取二级课程类型
	 * @param index
	 * @return
	 */
	@RequestMapping(value = "lessonType", method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String getLessonTwoType(int index) {

		JsonConfig config = new JsonConfig();
		config.setExcludes(new String[]{"oneType"});
		
		return JSONArray.fromObject(lessonOneTypes.get(index).getLessonTwoType(), config).toString();
	}
	
	/**
	 * 添加课程数据提交
	 * @param session
	 * @param data
	 * @return
	 */
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public String addLesson(HttpSession session, String data) {
		Map<String, Object> state = new HashMap<String, Object>();
		User teacher = (User) session.getAttribute("teacher");
		if(teacher == null) {
			state.put("isLogin", "no");
		}else {
			state.put("isLogin", "yes");
			System.out.println(data);
			Lesson lesson = (Lesson) JSONObject.toBean(JSONObject.fromObject(data), Lesson.class);
			lesson.setTeacher(teacher);
			if(serviceFac.getLessonService().addLesson(lesson)) {
				state.put("addLesson", "success");
				state.put("page", "lessonInfo");
			}else{
				state.put("addLesson", "fail");
			}
		}
		
		return JSONObject.fromObject(state).toString();
	}
}
